package com.zj.leetcode.hard.listNode;

/**
 * @program: algorithm
 * @description: K 个一组翻转链表
 * 25 reverse-nodes-in-k-group
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class ReverseNodesInKGroup {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4,
                                        new ListNode(5, null)))));

        ListNode head = new ListNode(5, null);
        Solution solution = new ReverseNodesInKGroup().new Solution();
        System.out.println(solution.reverseKGroup(head, 1));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {

            if (head == null || head.next == null) {
                return head;
            }


            int i = 0;
            int size = (int) this.size(head);
            int count = size / k;

            ListNode cur = head;
            ListNode pre = null;
            while (i < count) {
                int left = i * k;
                int right = i * k + k;
                ListNode newHead = cur;
                while (left < right - 1) {
                    ListNode next = cur.next;
                    cur.next = cur.next.next;
                    next.next = newHead;
                    if(right == k){
                        head = next;
                    }
                    newHead = next;
                    if (pre != null) {
                        pre.next = next;
                    }
                    left++;
                }
                ++i;
                pre = cur;
                cur = cur.next;
            }

            return head;
        }

        public long size(ListNode node) {
            int size = 0;
            while (node != null) {
                size++;
                node = node.next;
            }
            return size;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
